<?php
/**
 * Created by PhpStorm.
 * User: LiuJiaJun
 * Date: 2018/11/26
 * Time: 20:31
 */

namespace app\storage\model;
use think\Model;

class SupplierModel extends Model
{
    protected $table = 'iwh_supplier';
    protected $pk = 'uuid';

    public function getSupplier($condition)
    {
        $where = $condition['where'];
        unset($where['storage_uuid']);
        $pageSize = $condition['pageSize'];
        $pageIndex = $condition['pageIndex'];

        $ret['total'] = $this->count();
        $ret['row'] = $this->order('supplier_id asc')
            ->page($pageIndex, $pageSize)
            ->where($where)
            ->select();

        return $ret;
    }

    public function deleteSupplier($uuid)
    {
        $bomModel = new BomModel();
        $bom = $bomModel->where('supplier_uuid', $uuid)->select();
        if (count($bom)) {
            return ret_template(false, '已有该厂商的出库单，请先删除该厂商出库单');
        } else {
            $supplierId = $this->where('uuid', $uuid)->value('supplier_id');
            $this->startTrans();
            $tranSup = $this->where('uuid', $uuid)->delete();
            $supplierMaterielModel = new SupplierMaterielModel();
            $tranSm = $supplierMaterielModel->where('supplier_id', $supplierId)->delete();
            if ($tranSup != 0 && $tranSm !== false){
                $this->commit();
                return ret_template(true, '删除成功');
            }else{
                $this->rollback();
                return ret_template(false, '删除失败');
            }
        }
    }

    public function getSupplierInventory($condition)
    {
        $where = $condition['where'];
        $pageSize = $condition['pageSize'];
        $pageIndex = $condition['pageIndex'];
        if ($where['sub_materiel_id']) {
            $where['s.sub_materiel_id'] = $where['sub_materiel_id'];
            unset($where['sub_materiel_id']);

        }
        unset($where['storage_uuid']);//这个表不存在storage_uuid，但是where是封装好的，所以这边要去掉
        $supplierMateriel = new SupplierMaterielModel();

        $ret['total'] = $supplierMateriel->alias('s')
            ->join(['iwh_sub_materiel' => 'm'], 's.sub_materiel_id = m.sub_materiel_id', 'left')
            ->where($where)
            ->count();

        $ret['row'] = $supplierMateriel->alias('s')
            ->join(['iwh_sub_materiel' => 'm'], 's.sub_materiel_id = m.sub_materiel_id', 'left')
            ->field('s.sub_materiel_id,sub_materiel_name,count')
            ->order('s.sub_materiel_id asc')
            ->page($pageIndex, $pageSize)
            ->where($where)
            ->select();

        return $ret;
    }



    public function getCompany()
    {
        $result = $this->distinct(true)->field('supplier_id,company_name')->select();
        return $result;
    }

}

